"""
API响应工具类
"""
from typing import TypeVar, Generic, Optional, Any
from pydantic import BaseModel
from datetime import datetime

T = TypeVar('T')


class APIResponse(BaseModel, Generic[T]):
    """统一API响应格式"""
    code: int = 200
    message: str = "success"
    data: Optional[T] = None
    timestamp: datetime = datetime.now()
    
    class Config:
        json_encoders = {
            datetime: lambda v: v.isoformat()
        }


class PaginationResponse(BaseModel, Generic[T]):
    """分页响应格式"""
    items: list[T]
    total: int
    page: int
    size: int
    pages: int


def success_response(data: Any = None, message: str = "操作成功") -> APIResponse:
    """成功响应"""
    return APIResponse(
        code=200,
        message=message,
        data=data
    )


def created_response(data: Any = None, message: str = "创建成功") -> APIResponse:
    """创建成功响应"""
    return APIResponse(
        code=201,
        message=message,
        data=data
    )


def error_response(code: int = 500, message: str = "操作失败", data: Any = None) -> APIResponse:
    """错误响应"""
    return APIResponse(
        code=code,
        message=message,
        data=data
    )